#include "dialog2.h"
#include "ui_dialog2.h"

Dialog2::Dialog2(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog2)
{
    ui->setupUi(this);
}

Dialog2::Dialog2(QString dir, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog2)
{
    ui->setupUi(this);
    path_2 = dir;
    ui->lineEdit->setPlaceholderText("原密码");
    ui->lineEdit_2->setPlaceholderText("新密码");
    ui->lineEdit_3->setPlaceholderText("确认新密码");
    ui->lineEdit->setEchoMode(QLineEdit::Password);
    ui->lineEdit_2->setEchoMode(QLineEdit::Password);
    ui->lineEdit_3->setEchoMode(QLineEdit::Password);
}


Dialog2::~Dialog2()
{
    delete ui;
}

void Dialog2::on_pushButton_2_clicked()
{
    this->close();
}

void Dialog2::on_pushButton_clicked()
{
    QString pw;
    pw = ui->lineEdit->text();
    QFile file(path_2 + "//EnencryptedArea/password.txt");
    if(!file.open(QIODevice::ReadWrite | QIODevice::Text)){
        qDebug() << "Can't open the file!" << endl;
    }
    QTextStream in(&file);
    QString line = in.readLine();
    QByteArray bytePwd = pw.toLatin1();
    QByteArray bytePwdMd5 = QCryptographicHash::hash(bytePwd, QCryptographicHash::Md5);
    QString strPwdMd5 = bytePwdMd5.toHex();
    file.close();
    if (line == strPwdMd5){
        QString newpw1 = ui->lineEdit_2->text();
        QString newpw2 = ui->lineEdit_3->text();
        if (newpw1 == newpw2){
            file.open(QIODevice::ReadWrite | QIODevice::Truncate);
            QByteArray bytePwd_2 = newpw1.toLatin1();
            QByteArray bytePwdMd5_2 = QCryptographicHash::hash(bytePwd_2, QCryptographicHash::Md5);
            QString strPwdMd5_2 = bytePwdMd5_2.toHex();
            in << strPwdMd5_2;
            QMessageBox::warning(this, "Warning", "Successfully!");
            file.close();
            this->close();
        }
        else{
            QMessageBox::warning(this, "Warning", "Two password are different!");
        }
    }
    else{
        QMessageBox::warning(this, "Warning", "Wrong password！");
        //
    }

}
